package com.lagou.seaech.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.lagou.entity.Result;
import com.lagou.goods.pojo.Sku;
import com.lagou.seaech.Mapper.SearchMapper;
import com.lagou.seaech.service.SearchService;
import com.lagou.search.feign.SkuFeign;
import com.lagou.search.pojo.SkuInfo;
import lombok.AllArgsConstructor;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Fxz
 * @version 1.0
 * @date 2021-10-05 21:24
 */
@AllArgsConstructor
@Service
public class SearchServiceImpl implements SearchService {

    private static final Integer PAGE_SIZE = 5;

    private final SkuFeign skuFeign;

    private final SearchMapper searchMapper;

    private final ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 创建索引和映射
     */
    @Override
    public void createIndexAndMapping() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    /**
     * 导入所有符合上架条件的SKU列表
     *
     * @return
     */
    @Override
    public void importAll() {
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("status", "1");
        Result result = skuFeign.findList(paramMap);
        List<SkuInfo> skuInfos = JSON.parseArray(JSON.toJSONString(result.getData()), SkuInfo.class);
        for (SkuInfo skuInfo : skuInfos) {
            skuInfo.setSpecMap(JSON.parseObject(skuInfo.getSpec(), Map.class));
        }
        searchMapper.saveAll(skuInfos);
    }

    @Override
    public void addDataToEs(String spuId) {
        //通过id查SkuList
        List<Sku> listBySpuId = skuFeign.findListBySpuId(spuId);
        List<SkuInfo> skuInfos = JSON.parseArray(JSON.toJSONString(listBySpuId), SkuInfo.class);
        for (SkuInfo skuInfo : skuInfos) {
            skuInfo.setSpecMap(JSON.parseObject(skuInfo.getSpec(), Map.class));
        }
        searchMapper.saveAll(skuInfos);
    }

    @Override
    public Map<String, Object> search(Map<String, String> paramMap) {
        if (paramMap == null) {
            return null;
        }

        //返回结果集
        HashMap<String, Object> resultMap = new HashMap<>();

        //指定查询关键词 构建BoolQueryBuilder
        BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(paramMap);

        //指定过滤条件
        fieldsFilter(paramMap, boolQueryBuilder);

        //构建查询条件
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);

        //添加品牌聚合
        String skuBrand = "skuBrand";
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

        //添加规格聚合
        String skuSpec = "skuSpec";
        nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword").size(10000));

        //设置高亮区域
        setHighlight(nativeSearchQueryBuilder);

        //设置排序
        setOrder(paramMap, nativeSearchQueryBuilder);

        //设置分页
        setPageInfo(paramMap, nativeSearchQueryBuilder);

        //执行查询
        AggregatedPage<SkuInfo> aggregatedPage = executeQuery(nativeSearchQueryBuilder);

        //获取品牌聚合
        List<String> brandList = getBrandAgg(skuBrand, aggregatedPage);

        //获取规格聚合
        Map<String, Set<String>> specMap = getSpecAgg(skuSpec, aggregatedPage);

        //获取相关信息
        resultMap.put("rows", aggregatedPage.getContent());
        resultMap.put("total", aggregatedPage.getTotalElements());
        resultMap.put("totalPages", aggregatedPage.getTotalPages());
        resultMap.put("brandList", brandList);
        resultMap.put("specList", specMap);

        return resultMap;
    }

    private Map<String, Set<String>> getSpecAgg(String skuSpec, AggregatedPage<SkuInfo> aggregatedPage) {
        //获取聚合规格信息
        List<String> specTermList = getBrandAgg(skuSpec, aggregatedPage);
        Map<String, Set<String>> specMap = new HashMap<>();
        for (String spec : specTermList) {
            //将JSON转化为Map
            Map<String, String> map = JSON.parseObject(spec, Map.class);
            //遍历Map
            Set<Map.Entry<String, String>> entries = map.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String key = entry.getKey();
                String value = entry.getValue();
                Set<String> values = specMap.get(key);
                if (values == null) {
                    values = new HashSet<>();
                }
                values.add(value);
                specMap.put(key, values);
            }
        }
        return specMap;
    }

    private List<String> getBrandAgg(String skuBrand, AggregatedPage<SkuInfo> aggregatedPage) {
        //获取聚合品牌信息
        StringTerms brandTerms = aggregatedPage.getAggregations().get(skuBrand);
        return brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
    }

    /**
     * 执行查询
     *
     * @param nativeSearchQueryBuilder
     * @return
     */
    private AggregatedPage<SkuInfo> executeQuery(NativeSearchQueryBuilder nativeSearchQueryBuilder) {
        //执行查询
        AggregatedPage<SkuInfo> aggregatedPage = elasticsearchTemplate.queryForPage(
                nativeSearchQueryBuilder.build(),
                SkuInfo.class,
                new SearchResultMapper() {
                    /**
                     *  高亮数据替换非高亮数据
                     * @param searchResponse 封装了返回的结果集
                     * @param aClass    映射类型
                     * @param pageable 分页对象
                     */
                    @Override
                    public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                        List<T> list = new LinkedList<>();
                        //获得查询命中结果集
                        SearchHits hits = searchResponse.getHits();
                        //遍历结果集 替换高亮内容
                        hits.forEach(searchHit -> {
                            //获取命中的数据(没有高亮)
                            SkuInfo skuInfo = JSON.parseObject(searchHit.getSourceAsString(), SkuInfo.class);
                            //获取高亮的数据
                            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
                            //如果指定了高亮域
                            if (highlightFields != null && highlightFields.size() > 0) {
                                //获取其中的name字段
                                HighlightField highlightField = highlightFields.get("name");
                                if (highlightField != null) {
                                    //取出高亮数据
                                    Text[] fragments = highlightField.getFragments();
                                    StringBuffer stringBuffer = new StringBuffer();
                                    Arrays.stream(fragments).forEach(text -> stringBuffer.append(text.toString()));
                                    //替换
                                    skuInfo.setName(stringBuffer.toString());
                                    list.add((T) skuInfo);
                                }
                            }
                        });
                        return new AggregatedPageImpl<>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                    }
                });
        return aggregatedPage;
    }

    private void setPageInfo(Map<String, String> paramMap, NativeSearchQueryBuilder nativeSearchQueryBuilder) {
        //设置分页
        String pageNum = paramMap.get("pageNum");
        if (StringUtils.isEmpty(pageNum)) {
            pageNum = "1";
        }
        nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, PAGE_SIZE));
    }

    /**
     * 设置排序
     *
     * @param paramMap
     * @param nativeSearchQueryBuilder
     */
    private void setOrder(Map<String, String> paramMap, NativeSearchQueryBuilder nativeSearchQueryBuilder) {
        //设置排序
        String sortField = paramMap.get("sortField");
        String sortRule = paramMap.get("sortRule");
        if (!StringUtils.isEmpty(sortField) && !StringUtils.isEmpty(sortRule)) {
            nativeSearchQueryBuilder.withSort(new FieldSortBuilder(sortField).order(SortOrder.valueOf(sortRule.toUpperCase())));
        }
    }

    /**
     * 设置高亮区域
     *
     * @param nativeSearchQueryBuilder
     */
    private void setHighlight(NativeSearchQueryBuilder nativeSearchQueryBuilder) {
        //设置高亮域
        HighlightBuilder.Field field = new HighlightBuilder.Field("name");
        field.preTags("<span style='color:red'>");
        field.postTags("</span>");
        nativeSearchQueryBuilder.withHighlightFields(field);
    }

    /**
     * 指定过滤条件
     *
     * @param paramMap
     * @param boolQueryBuilder
     */
    private void fieldsFilter(Map<String, String> paramMap, BoolQueryBuilder boolQueryBuilder) {
        //添加品牌过滤
        if (!StringUtils.isEmpty(paramMap.get("brand"))) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brandName", paramMap.get("brand")));
        }

        //添加规格过滤
        paramMap.keySet().forEach(key -> {
            if (key.startsWith("spec_")) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("specMap." + key.substring(5) + ".keyword", paramMap.get(key)));
            }
        });

        //添加价格过滤
        if (!StringUtils.isEmpty(paramMap.get("price"))) {
            String price = paramMap.get("price");
            price = price.replace("元", "").replace("以上", "");
            String[] prices = price.split("-");
            if (ArrayUtil.isNotEmpty(prices)) {
                boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
                if (prices.length == 2) {
                    boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
            }
        }
    }

    /**
     * 获取查询关键词 构建BoolQueryBuilder
     *
     * @param paramMap
     * @return
     */
    private BoolQueryBuilder getBoolQueryBuilder(Map<String, String> paramMap) {
        //获取查询关键词
        String keywords = paramMap.get("keywords");
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchQuery("name", keywords).operator(Operator.AND));
        return boolQueryBuilder;
    }
}
